import Vue from 'vue'
import axios from 'axios'

import qsp from 'qs'

// 全局注册工具
// import utils from './utilsTools.js'
// Vue.prototype.$utils = utils
import { getStorage } from './utilsTools.js'

const service = axios.create({
	baseURL: 'https://microaccount.mumuwei.xyz/micro_account/',
	// baseURL: 'http://127.0.0.1:8668/micro_account/',
	transformRequest: [function(data) {
	    // 对 data 进行任意转换处理
	    return qsp.stringify(data)
	    // return data
	  }],
	  // withCredentials: true, // send cookies when cross-domain requests
	  timeout: 5000 // request timeout
})

// request 过滤
service.interceptors.request.use(
  config => {

    if (getStorage('uid') != undefined & getStorage('uid') != '') {
      config.headers['uid'] = getStorage('uid')
    }
	if (getStorage('token') != undefined & getStorage('token') != '') {
	  config.headers['token'] = getStorage('token')
	}
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or static
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
	if(res.code === 502){
		uni.clearStorage()
	}
	return res
    // 判断是excel下载，直接放行
    // if (res.type === 'application/vnd.ms-excel') {
    //   return res
    // }
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 200) {
    //   console.log(res)
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  }, error => {
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log("执行完成：", response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

export default service